//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package idea_dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/idea_store_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type IdeaStoreCateDbItem struct {
	StoreCateId string `bson:"_id" json:"_id"`
	Name        string `bson:"name" json:"name"`
	Weight      uint32 `bson:"weight" json:"weight"`
	StoreCount  uint32 `bson:"storeCount" json:"storeCount"`
}

func (item *IdeaStoreCateDbItem) ToIdeaStoreCate() *idea_store_api.IdeaStoreCate {
	return &idea_store_api.IdeaStoreCate{
		StoreCateId: item.StoreCateId,
		Name:        item.Name,
		Weight:      item.Weight,
		StoreCount:  item.StoreCount,
	}
}

type _IdeaStoreCateDao struct {
	mc *mongo.Collection
}

func newIdeaStoreCateDao(db *mongo.Database) (*_IdeaStoreCateDao, error) {
	mc := db.Collection(db_ns.DB_NS_PROJECT_IDEA + "store_cate")
	return &_IdeaStoreCateDao{mc: mc}, nil
}

func (db *_IdeaStoreCateDao) Insert(ctx context.Context, dbItem *IdeaStoreCateDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_IdeaStoreCateDao) Exist(ctx context.Context, storeCateId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": storeCateId})
	return count > 0, err
}

func (db *_IdeaStoreCateDao) Get(ctx context.Context, storeCateId string) (*IdeaStoreCateDbItem, error) {
	retItem := &IdeaStoreCateDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": storeCateId}).Decode(retItem)
	return retItem, err
}

func (db *_IdeaStoreCateDao) Remove(ctx context.Context, storeCateId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": storeCateId})
	return err
}

func (db *_IdeaStoreCateDao) List(ctx context.Context) ([]*IdeaStoreCateDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{}, options.Find().SetSort(bson.M{"weight": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*IdeaStoreCateDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_IdeaStoreCateDao) UpdateNameAndWeight(ctx context.Context, storeCateId, name string, weight uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": storeCateId},
		bson.M{"$set": bson.M{"name": name, "weight": weight}})
	return err
}

func (db *_IdeaStoreCateDao) UpdateStoreCount(ctx context.Context, storeCateId string, count uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": storeCateId},
		bson.M{"$set": bson.M{"storeCount": count}})
	return err
}
